package cn.gson.boot.model.service;

import cn.gson.boot.model.dao.CategoryDao;
import cn.gson.boot.model.mapper.CategoryMapper;
import cn.gson.boot.model.pojos.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CategoryService {
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    CategoryDao categoryDao;

    //查询一级
    public List<CategoryType> parentType(){
        return categoryMapper.selectAllCategory(null);
    }
    //查询子级
    public List<CategoryType> CategoryTypes(CategoryType parentType){
        //根据父级查询子级
        List<CategoryType> categoryTypes = categoryMapper.selectAllCategory(parentType.getCategoryId());
        //循环当前级别
        for (CategoryType categoryType : categoryTypes) {
            //递归调用查询子级的方法，查询该级别下的子级，并赋值到该级别下的子级集合
            categoryType.setCategoryTypes(this.CategoryTypes(categoryType));
        }
        return categoryTypes;
    }

    //查询所有类别
    public List<CategoryType> selectAllCategory(){
        //查询一级
        List<CategoryType> parentType = this.parentType();
        //查询一级下的二级，在这个方法里，会递归查询子级
        for (CategoryType categoryType : parentType) {
            categoryType.setCategoryTypes(this.CategoryTypes(categoryType));
        }
        return parentType;
    }

    //修改类别时查询上级类别
    public Category selectCategoryIdt(Integer categoryId) {
        return categoryMapper.selectCategoryIdt(categoryId);
    }

    //新增类别
    public void addCategory(Category category) {
        category.setCategorySc(0);
        System.out.println(category);
        categoryDao.save(category);
    }

    //删除时查询是否有下级类别
    public List<Category> selectCategoryt(Integer categoryId) {
        return categoryMapper.selectCategoryt(categoryId);

    }

    //删除类别
    public void delCategory(Integer categoryId) {
        Category category = categoryDao.findById(categoryId).get();
        category.setCategorySc(1);
        System.out.println("修改后"+category);
        categoryDao.save(category);
    }


}
